package com.nerve.android.cloudoffice.app.activity.task;

import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;
import org.nerve.android.ui.dialog.ConfirmDialog;
import org.nerve.android.ui.dialog.DialogHelper.ConfirmListener;
import org.nerve.android.ui.dialog.SpinnerDialog;
import org.nerve.util.DateUtil;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.activity.assist.UserSelectActivity;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.common.Resource;
import com.nerve.android.cloudoffice.domain.Task;
import com.nerve.android.cloudoffice.service.NetService;
import com.nerve.android.cloudoffice.service.data.TaskData;

/**
 * @project: Cloudoffice_android
 * @file: ViewTaskActivity.java
 * @package: com.nerve.android.cloudoffice.app.activity.task
 * @description:
 *	查看任务
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: Aug 17, 2013
 * @change log:
 */
@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.activity_task_view)
public class ViewTaskActivity extends NavigationActivity implements ConfirmListener, OnClickListener{
	
	public static final String VIEW_TASK = "view_task";
	public static final String IS_ME = "is_me";
	
	private static final int WORK_DEL = 1001;
	private static final int WORK_UPDATE = 1002;
	
	private static final int ACCEPT_OK = 2003;
	
	/*
	 * 更新的操作标识
	 */
	public static final int ACCEPT = 0;
	public static final int REJECT = 1;
	public static final int REDIRECT = 2;
	
	public static final String[] MENUS = {"更新任务进度", "修改重要等级", "申请删除任务", "增加任务备注"};
	
	@ViewOnId(id=R.id.name)
	private EditText nameET;
	@ViewOnId(id=R.id.sender)
	private EditText senderET;
	@ViewOnId(id=R.id.worker)
	private EditText workerET;
	@ViewOnId(id=R.id.level, clickListener="this")
	private EditText levelET;
	@ViewOnId(id=R.id.state)
	private TextView stateTV;
	@ViewOnId(id=R.id.seekbar)
	private SeekBar seekBar;
	@ViewOnId(id=R.id.startDate)
	private EditText startET;
	@ViewOnId(id=R.id.endDate)
	private EditText endET;
	@ViewOnId(id=R.id.message)
	private EditText messageET;
	@ViewOnId(id=R.id.acceptType)
	private EditText acceptET;
	@ViewOnId(id=R.id.okBtn, clickListener="this")
	public Button okBtn;
	
	@ViewOnId(id=R.id.remark)
	private EditText remarkET;
	@ViewOnId(id=R.id.tag)
	private EditText tagET;
	@ViewOnId(id=R.id.project)
	private EditText projectET;
	
	@ViewOnId(id=R.id.acceptBtn, clickListener="this")
	public Button acceptBtn;
	@ViewOnId(id=R.id.rejectBtn, clickListener="this")
	public Button rejectBtn;
	@ViewOnId(id=R.id.redirectBtn, clickListener="this")
	public Button redirtBtn;
	
	private Task task;
	private boolean isME;
	
	private SpinnerDialog levelSpinnerDialog;
	
	private ConfirmDialog deleteDialog;
	
	private int acceptType;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			hideProgressDialog();
			switch (msg.what) {
			case WORK_DEL:
				toast("删除申请提交成功，请等待上级审批");
				break;
			case WORK_UPDATE:
				toast("任务更新成功");
				break;
			case WORKER_FAIL:
				toast(Const.ERROR);
				break;
			case ACCEPT_OK:
				if(acceptType == ACCEPT){
					task.setLoaction(Task.ACCEPTED);
					
					acceptBtn.setVisibility(View.GONE);
					redirtBtn.setVisibility(View.GONE);
					rejectBtn.setVisibility(View.GONE);
					
					toast("接受任务成功");
				}
				else{
					task.setLoaction(
							acceptType == REJECT? Task.REJECT : Task.WAIT_ACCEPT
							);
					
					toast("操作任务成功");
					onNavigateBackButtonClick();
				}
				
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		setNavTitle("查看任务");
		
		//如果查看的不是自己的任务，不能操作
		if(isME)
			customNavigateRightButton("删除任务", true);
		else{
			okBtn.setVisibility(View.GONE);
		}
		
		resetBtn();
		showTask();
	}
	
	private void resetBtn(){
		//先全部隐藏，再选择性显示
		
		int acceptV = View.GONE;
		int rejectV = View.GONE;
		int redirectV = View.GONE;
		
		if(isME){
			if(task.getLoaction() == Task.WAIT_ACCEPT){
				acceptV = View.VISIBLE;
				redirectV = View.VISIBLE;
				rejectV = View.VISIBLE;
			}
		}
		
		acceptBtn.setVisibility(acceptV);
		rejectBtn.setVisibility(rejectV);
		redirtBtn.setVisibility(redirectV);
	}
	
	@Override
	protected void initData() {
		super.initData();
		
		Object obj = getData(VIEW_TASK, true);
		if(obj != null && obj instanceof Task)
			task = (Task)obj;
		
		isME = getIntent().getBooleanExtra(IS_ME, false);
	}
	
	private void showTask(){
		if(task == null){
			toast("没有可以显示的任务，请返回重新选择");
			return ;
		}
		
		nameET.setText(task.getTitle());
		senderET.setText(task.getSendUser());
		workerET.setText(task.getWorkUser());
		levelET.setText(Resource.Task.LEVEL[task.getLevel()]);
		startET.setText(DateUtil.toString(task.getStartDate(), "yyyy-MM-dd"));
		endET.setText(DateUtil.toString(task.getEndDate(), "yyyy-MM-dd"));
		messageET.setText(task.getMessage());
		stateTV.setText("进度("+task.getStatus()+"%):");
		acceptET.setText(
				Resource.Task.LOCATION[task.getLoaction()]
				);
		
		remarkET.setText(task.getRemark());
		tagET.setText(task.getTag());
		projectET.setText(task.getProject());
		
		buildSeekbar();
	}
	
	private void buildSeekbar(){
		seekBar.setProgress(task.getStatus());
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
			}
			
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				task.setStatus(arg0.getProgress());
				stateTV.setText("进度("+task.getStatus()+"%):");
			}
		});
	}
	
	@Override
	protected void onNavigateRightButtonClick() {
		if(deleteDialog == null){
			deleteDialog = new ConfirmDialog(
					ViewTaskActivity.this, 
					"删除任务", 
					"任务不能直接删除，只能提交删除申请，由上级审批通过后方可删除任务。您现在要提交删除申请吗？"
					);
			deleteDialog.setConfirmListener(new ConfirmListener() {
				@Override
				public void onConfirmClick(int position, Object obj) {
					if(position == ConfirmDialog.OK){
						new ViewWorker().execute(WORK_DEL);
					}
				}
			});
		}
		
		deleteDialog.show();
	}

	@Override
	public void onConfirmClick(int position, Object obj) {
		levelET.setText(Resource.Task.LEVEL[position]);
		task.setLevel(position);
	}

	@Override
	public void onClick(View v) {
		if(!isME)
			return ;
		
		switch(v.getId()){
		case R.id.level:
			if(levelSpinnerDialog == null){
				levelSpinnerDialog = new SpinnerDialog(this, Resource.Task.LEVEL);
				levelSpinnerDialog.setCode(AddTaskActivity.SELECT_LEVEL);
				levelSpinnerDialog.setTitle("选择任务重要度");
				levelSpinnerDialog.setConfirmListener(this);
			}
			levelSpinnerDialog.show();
			break;
			
		case R.id.okBtn:
			//保存修改
			task.setMessage(messageET.getText().toString());
			task.setProject(getText(projectET));
			task.setRemark(getText(remarkET));
			task.setTag(getText(tagET));
			
			new ViewWorker().execute(WORK_UPDATE);
			break;
			
		case R.id.acceptBtn:
			acceptType = ACCEPT;
			
			ConfirmDialog acceptD = new ConfirmDialog(this, "接受任务", 
					"确定要接受'" + task.getTitle()+"'这个任务吗？");
			acceptD.setConfirmListener(new ConfirmListener() {
				
				@Override
				public void onConfirmClick(int position, Object obj) {
					if(position == ConfirmDialog.OK)
						new AcceptWorker().execute(acceptType);
				}
			});
			
			acceptD.show();
			break;
			
		case R.id.redirectBtn:
			acceptType = REDIRECT;
			Intent intent = new Intent(this, UserSelectActivity.class);
			startActivityForResult(intent, REDIRECT);
			break;
		case R.id.rejectBtn:
			acceptType = REJECT;
			
			acceptD = new ConfirmDialog(this, "拒绝任务", 
					"确定要拒绝'" + task.getTitle()+"'这个任务吗？");
			acceptD.setConfirmListener(new ConfirmListener() {
				
				@Override
				public void onConfirmClick(int position, Object obj) {
					if(position == ConfirmDialog.OK)
						new AcceptWorker().execute(acceptType);
				}
			});
			
			acceptD.show();
			break;
		}
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null)
			return ;
		
		/*
		 * 选择职员返回时
		 */
		if(requestCode == REDIRECT){
			int id = data.getIntExtra(UserSelectActivity.ID, -1);
			
			if(id > 0){
				new AcceptWorker().execute(acceptType, id);
			}
		}
	}
	
	private class ViewWorker extends AsyncTask<Integer, Void, Integer>{

		@Override
		protected Integer doInBackground(Integer... params) {
			Reply re = null;
			if(params[0] == WORK_DEL){
				re = TaskData.update(task.getId(), TaskData.DELETE, "");
			}else{
				re = TaskData.updateTask(task);
			}
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return WORKER_FAIL;
			}
			return params[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
	}
	
	private class AcceptWorker extends AsyncTask<Integer, Void, Integer>{

		@Override
		protected Integer doInBackground(Integer... params) {
			int workerId = params.length < 2?0:params[1];
			
			Reply re = NetService.get(Const.HOST + "task/accept.htm?id=" 
						+ task.getId() + "&updateType=" + params[0] +"&updateValue=" + workerId);
			
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return WORKER_FAIL;
			}
			
			return ACCEPT_OK;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
		
	}
}